<?php

namespace App\Models\CacheModel\ai_chat_room;

use App\Models\CacheModel\ZlUserVip;
use App\Models\Api\BaseCache;
use AstroTool\Cache\CacheManage;

class AiChatUserDurationChangeRecord extends BaseCache
{
    protected $table = 'ai_chat_room.ai_chat_user_duration_change_record';

    protected $cacheModel = 'ai_chat_room.user_duration_change_record';

    public function SaveData(array $data)
    {
        try
        {
            $id = $this->insertGetId($data);

            return (int)$id;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    /**
     * 减少用户陪聊时长
     * @param array $durationData
     * @param int $decDuration
     * @return array
     */
    public function userDurationDec(array $durationData, int $decDuration = 0)
    {
        $endDuration = $decDuration;
        $vipUseDuration = 0;
        $useDuration = 0;
        $oldVipUseDuration = 0;
        if ($durationData['vip_duration'] > 0)
        {
            if ($durationData['vip_duration'] >= $endDuration)
            {   // vip时长大于要减少的时长
                $vipUseDuration = $endDuration;
                $endDuration = 0;
            } else
            {
                $vipUseDuration = $durationData['vip_duration'];
                $endDuration = $endDuration - $vipUseDuration;
            }
            $oldVipUseDuration = $this->getTodayVipUseDuration($durationData['uid']);
        }
        if ($endDuration > 0)
        {   // 还有 需要扣除时长
            if ($durationData['duration'] >= $endDuration)
            {
                $useDuration = $endDuration;
            } else
            {
                $useDuration = $durationData['duration'];
            }
        }
        $date = (int)date('Ymd');
        $insterData = [
            'uid' => $durationData['uid'],
            'type' => 3,
            'gid' => 0,
            'order_id' => '',
            'change_duration' => $useDuration,
            'vip_change_duration' => $vipUseDuration,
            'res_duration' => $durationData['duration'] - $useDuration,
            'res_vip_duration' => $durationData['vip_duration'] - $vipUseDuration,
            'date' => $date,
            'remark' => '',
            'create_time' => time(),
        ];
        $this->SaveData($insterData);
        if ($vipUseDuration > 0)
        {
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('vip_use_duration', "{$durationData['uid']}:{$date}")->setCacheTime(10)->setCache(['vip_duration' => $oldVipUseDuration + $vipUseDuration], 'vip_use_duration');
        }
        return [
            'vip_use_duration' => $vipUseDuration,
            'use_duration' => $useDuration,
        ];
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        // 获取未删除 的数据
        $where = ['id' => ['in', $ids]];
        try
        {
            $data = $this->where($where)->column('*', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }


    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'type', 'gid', 'change_duration', 'vip_change_duration', 'res_duration', 'res_vip_duration', 'date', 'create_time']);
        }

        return $data;
    }

    public function getTodayVipUseDuration(int $uid)
    {
        $date = (int)date('Ymd');
        $vipUseDuration = CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('vip_use_duration', "{$uid}:{$date}")->getDataAndSet(function () use ($uid, $date)
        {
            try
            {
                $vipChangeDuration = $this->where(['uid' => $uid, 'type' => 3, 'date' => $date])->sum('vip_change_duration');

                return ['vip_duration' => (int)$vipChangeDuration];
            }
            catch (\Exception $e)
            {
                \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                return [];
            }
        }, [], 'vip_use_duration');

        return (int)($vipUseDuration['vip_duration'] ?? 0);
    }

    /**
     * 获取 用户聊天时长 已完成聊天时长任务IDS
     * @param int $uid
     * @return array
     * @throws \Exception
     */
    public function getTaskSuccessData(int $uid)
    {
        $sucTaskData = CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('task_suc_record', $uid)->getDataAndSet(function () use ($uid)
        {
            try
            {
                $taskIds = $this->where(['uid' => $uid, 'type' => 2])->column('gid');

                return ['task_ids' => json_encode($taskIds, JSON_UNESCAPED_UNICODE)];
            }
            catch (\Exception $e)
            {
                \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                return [];
            }
        }, [], 'task_suc_record');

        $taskIds = isset($sucTaskData['task_ids']) && $sucTaskData['task_ids'] ? json_decode($sucTaskData['task_ids'], true) : [];
        $resTaskIds = [];
        foreach ($taskIds as $id)
        {
            $resTaskIds[] = (int)$id;
        }
        $vipLevel = (new ZlUserVip())->getUserVipLevel($uid);
        if ($vipLevel)
        {
            $resTaskIds[] = 2;
        }
        return $resTaskIds;
    }

    /**
     * 聊天时长任务完成
     * @param int $uid
     * @param int $taskId
     * @return array
     * @throws \Exception
     */
    public function durationTaskSuccess(int $uid, int $taskId)
    {
        try
        {
            $nowTime = time();
            $aiChatUserDurationModel = new AiChatUserDuration();
            $sucTaskIds = $this->getTaskSuccessData($uid);
            // 获取 用户当前 剩余陪聊时长
            if (in_array($taskId, $sucTaskIds))
            {
                $chatDuration = $aiChatUserDurationModel->getUserDuration($uid);
                return [
                    'status' => 1,
                    'duration' => $chatDuration['res_duration'],
                ];
            }
            $taskConfig = config('ai_chat_room.task_data');
            $taskData = $taskConfig['list'][$taskId];
            $durationData1 = $aiChatUserDurationModel->getChatUserDurationData($uid);
            $durationData1['duration'] = $durationData1['duration'] + $taskData['duration'];
            $durationData1['total_duration'] = $durationData1['total_duration'] + $taskData['duration'];
            //  增加 聊天时长
            $aiChatUserDurationModel->UpdateData($uid, [
                'duration' => $durationData1['duration'],
                'total_duration' => $durationData1['total_duration'],
                'update_time' => $nowTime,
            ]);
            // 增加 聊天时长 变更记录
            $insterData = [
                'uid' => $uid,
                'type' => 2,
                'gid' => $taskId,
                'order_id' => '',
                'change_duration' => $taskData['duration'],
                'vip_change_duration' => 0,
                'res_duration' => $durationData1['duration'],
                'res_vip_duration' => $durationData1['vip_duration'],
                'date' => 0,
                'remark' => '',
                'create_time' => $nowTime,
            ];
            $this->SaveData($insterData);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('task_suc_record', $uid)->rmCache('task_suc_record');
            $durationData1['res_duration'] += $taskData['duration'];
            if ($durationData1['status'] === 1)
            {
                $nowTime = time();
                $d1 = $durationData1['last_send_time'] - $durationData1['start_time'];
                $d1 = max($d1, 0);
                $d2 = $nowTime - $durationData1['last_send_time'];
                $d2 = min($d2, 30); // 进行中 最多30秒
                $d = $d1 + $d2;
                $durationData1['res_duration'] = $durationData1['res_duration'] - $d;
            }

            return [
                'status' => 2,
                'duration' => $durationData1['res_duration'],
            ];
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);

            return [
                'status' => -1,
                'msg' => '服务异常，请稍后再试～',
            ];
        }
    }
}
